package com.project.controller.web;

import com.alibaba.fastjson.JSONObject;
import com.project.common.utils.MyPageHelper;
import com.project.entity.Resource;
import com.project.entity.RoleResource;
import com.project.entity.User;
import com.project.entity.UserRole;
import com.project.myBeans.R;
import com.project.myBeans.ResponseBean;
import com.project.service.ResourceService;
import com.project.service.RoleResourceService;
import com.project.service.UserRoleService;
import com.project.service.base.BaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: TateBrown
 * @date: 2018/5/27 16:30
 * @param:
 * @return:
 */
@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping(value = "/resource")
@Api(description = "资源相关",value = "resource")
public class ResourceController extends BaseService{
    @Autowired
    private ResourceService resourceService;

    @Autowired
    private RoleResourceService roleResourceService;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * TateBrown 2018年5月27日
     *
     * @param resource
     * @return
     */
    @ApiOperation(" 根据条件模糊查找资源")
    @PostMapping("/findByCondition")
    public R findByCondition(@RequestBody Resource resource) {
        List<Resource> resourceList;
        try {
            MyPageHelper.setPageParam(resource);
            resource.setPageIndex(resource.getPageIndex() - 1);
            resourceList = resourceService.findByCondition(resource);
          return R.ok().put("data",resourceList).put("total", MyPageHelper.getTotal(resourceList));
        } catch (Exception e) {
            e.printStackTrace();
          return R.error().put("data",null);
        }
    }

    /**
     * TateBrown 2018年5月27日
     *
     * @param resource
     * @return
     */
    @ApiOperation(" 根据条件模糊查找一级菜单及其以下子菜单")
    @PostMapping("/findByCondition3")
    public R findByCondition3(@RequestBody Resource resource) {
        List<Resource> resourceList;
        try {
            MyPageHelper.setPageParam(resource);
            resource.setPageIndex(resource.getPageIndex() - 1);
            resource.setLevel(1);

            resourceList = resourceService.findByCondition(resource);
            List<JSONObject> jsonObjectList = new ArrayList<>();
            for (Resource resource1: resourceList) {
                JSONObject jsonObject = new JSONObject();
                //设置筛选条件
                Resource resource2 = new Resource();
                resource2.setPid(resource1.getId());
                //查出菜单下的子菜单
                resource2.setAvailable(1);
                List<Resource> resourceList1 = resourceService.findByCondition(resource2);
                jsonObject.put("parent", resource1);
                jsonObject.put("children", resourceList1);
                jsonObjectList.add(jsonObject);
            }

            return R.ok().put("data",jsonObjectList).put("total",MyPageHelper.getTotal(jsonObjectList));
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().put("data",null);
        }
    }
    /**
     * TateBrown 2018年5月27日
     *
     * @param resource
     * @param session
     * @return
     */
    @ApiOperation("角色授权：获取资源的同时，获取某个角色所拥有的资源")
    @PostMapping("/findByCondition2")
    public Object findByCondition2(@RequestBody Resource resource, HttpSession session) {
        List<Resource> resourceList = null;
        List<RoleResource> roleResourceList;
        JSONObject jsonObject = new JSONObject();
        int roleid = resource.getRoleid();

        try {
            //若是系统管理员，则找出全部资源；否则只找出该用户所属角色拥有的资源
            User user = (User) session.getAttribute("currentUser");
            if (user != null && user.getUsertype() == 5) { //系统管理员
                resource.setAvailable(1); //找可显示的资源
                resourceList = resourceService.findByCondition(resource); //资源列表
            } else {
                //找出该用户所属角色拥有的资源id集合
                List<UserRole> userRoles = userRoleService.findResourcesByUserId(user.getId());
                List<Integer> integerIds = new ArrayList<Integer>();
                for (UserRole userRole : userRoles) {
                    integerIds.add(userRole.getResourceid());
                }
                //再找资源
                if (integerIds.size() > 0)
                    resourceList = resourceService.findByIds(integerIds);
            }

            //某个角色所拥有的资源
            roleResourceList = roleResourceService.findByRoleId(roleid);

            jsonObject.put("data", resourceList);
            jsonObject.put("data1", roleResourceList);
            jsonObject.put("success", true);
            jsonObject.put("total", resource.getTotal());

        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("success", false);
            jsonObject.put("data", null);
            jsonObject.put("data1", null);
        }

        return jsonObject;
    }
    /**
     * TateBrown 2018年5月27日
     *
     * @param resource
     * @return
     */
    @ApiOperation("添加单个资源")
    @PostMapping("/addOne")
    public R addOne(@RequestBody Resource resource) {
        try {
            resourceService.addOne(resource);
            return R.ok("操作成功");
        } catch (Exception e) {
            return R.error("操作失败");
        }
    }

    /**
     * TateBrown 2018年5月27日
     *
     * @param resource
     * @return
     */
    @ApiOperation("根据id修改相应资源")
    @PostMapping("/modifyOneById")
    public R modifyOneById(@RequestBody Resource resource) {
        try {
            resourceService.modifyOneById(resource);
            return R.ok("操作成功");
        } catch (Exception e) {
            return R.error("操作失败");
        }
    }
    /**
     * TateBrown 2018年5月27日
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id删除相应资源,及相应子菜单")
    @GetMapping("/removeOneById/{id}")
    public R removeOneById(@PathVariable int id) {

        try {
            Resource resourcecondition = new Resource();
            resourcecondition.setPid(id);
            List<Resource> childrenResources = resourceService.findByCondition(resourcecondition);
            for (Resource child : childrenResources) {
                resourceService.removeOneById(child.getId());
            }
            resourceService.removeOneById(id);
            return R.ok("操作成功");
        } catch (Exception e) {
            return R.error("操作失败");
        }
    }
    /**
     * TateBrown 2018年5月27日
     *
     * @param id
     * @return
     */
    @ApiOperation("根据资源表主键查找单条资源")
    @GetMapping("/findOneById/{id}")
    public R findOneById(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            return R.ok("查找成功").put("data",resourceService.findOneById(id));
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
}
